// pages/report/report_page.dart (*** NEW AND IMPROVED ***)
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import '../../bloc/report/report_bloc.dart';
import '../../bloc/report/report_data.dart';
import '../../bloc/report/report_event.dart';
import '../../models/report_data.dart';
import '../../widgets/financial_card.dart';
import '../../widgets/year_toggle_buttons.dart';


class ReportPage extends StatefulWidget {
  const ReportPage({super.key});

  @override
  State<ReportPage> createState() => _ReportPageState();
}

class _ReportPageState extends State<ReportPage> with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin{
  @override
  bool get wantKeepAlive => true;

  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    // Initial data load for the default year
    context.read<ReportBloc>().add(LoadReportData("year","2025"));
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('章鱼问账'),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
        bottom: TabBar(
          controller: _tabController,
          labelColor: const Color(0xFF4DD0E1),
          unselectedLabelColor: Colors.grey,
          indicatorColor: const Color(0xFF4DD0E1),
          indicatorSize: TabBarIndicatorSize.label,
          tabs: const [
            Tab(text: '利润表'),
            Tab(text: '资产负债表'),
            Tab(text: '纳税报表'),
          ],
        ),
      ),
      body: BlocBuilder<ReportBloc, ReportState>(
        builder: (context, state) {
          if (state is ReportLoading) {
            return const Center(child: SpinKitFadingCircle(color: Color(0xFF4DD0E1)));
          }
          if (state is ReportLoadSuccess) {
            return _buildReportContent(context, state.reportData);
          }
          if (state is ReportLoadFailure) {
            return Center(child: Text('加载失败: ${state.error}'));
          }
          return const Center(child: Text('请选择年份加载数据'));
        },
      ),
    );
  }

  Widget _buildReportContent(BuildContext context, ReportData data) {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        _buildChartCard(
          context,
          '利润趋势图',
          data.year,
          data.profitTrend,
              (year) => context.read<ReportBloc>().add(LoadReportData("year","data.startPeriod")),
        ),
        const SizedBox(height: 20),
        _buildChartCard(
          context,
          '纳税分析图',
          data.year,
          data.taxTrend,
              (year) => context.read<ReportBloc>().add(LoadReportData("year","data.startPeriod")),
        ),
        const SizedBox(height: 20),
        _buildRiskReportCard(),
      ],
    );
  }

  Widget _buildChartCard(BuildContext context, String title, int currentYear, List<ChartDataPoint> points, Function(int) onYearChanged) {
    return FinancialCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
              YearToggleButtons(
                selectedYear: currentYear,
                onYearSelected: onYearChanged,
              ),
            ],
          ),
          const SizedBox(height: 24),
          SizedBox(
            height: 180,
            child: LineChart(
              _createLineChartData(points),
            ),
          ),
        ],
      ),
    );
  }

  LineChartData _createLineChartData(List<ChartDataPoint> points) {
    return LineChartData(
      gridData: FlGridData(
        show: true,
        drawVerticalLine: false,
        getDrawingHorizontalLine: (value) {
          return const FlLine(color: Color(0xffe7e8ec), strokeWidth: 1);
        },
      ),
      titlesData: FlTitlesData(
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 30,
            interval: 1,
            getTitlesWidget: (value, meta) {
              final index = value.toInt();
              if (index >= 0 && index < points.length) {
                return Text('data ');
                // return SideTitleWidget(
                //   // axisSide: meta.axisSide,
                //   space: 8.0,
                //   meta: TitleMeta(axisSide: meta.axisSide,parentAxisSize: ),
                //   child: Text(points[index].label, style: const TextStyle(color: Colors.grey, fontSize: 12)),
                // );
              }
              return const Text('');
            },
          ),
        ),
        leftTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
        topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
        rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
      ),
      borderData: FlBorderData(show: false),
      lineBarsData: [
        LineChartBarData(
          spots: points.asMap().entries.map((e) => FlSpot(e.key.toDouble(), e.value.value)).toList(),
          isCurved: true,
          color: const Color(0xFF4DD0E1),
          barWidth: 4,
          isStrokeCapRound: true,
          dotData: FlDotData(show: false),
          belowBarData: BarAreaData(
            show: true,
            gradient: LinearGradient(
              colors: [
                const Color(0xFF4DD0E1).withOpacity(0.3),
                const Color(0xFF4DD0E1).withOpacity(0.0),
              ],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildRiskReportCard() {
    return FinancialCard(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          const Text('企业税务风险检测报告', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
          ElevatedButton(
            onPressed: () {},
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF4DD0E1),
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            ),
            child: const Text('开始评估'),
          ),
        ],
      ),
    );
  }
}